# coding=utf-8

import os, re, json
from datetime import timedelta, datetime
from flask import render_template, redirect, url_for, request, session, current_app, flash, Flask, \
    make_response, jsonify, abort
from flask_login import login_required, current_user
from uuid import uuid4

from . import blue_duty
from .. import db
from .forms import CreateUser
from .uploader import Uploader
from ..models import User, Duty, BandWidth, RichText, OPEvent, Group, Picture, TempText, DailyInfo, EngineRoom, \
    EmailStatus, Email
from app.BlueDuty.sendemail import send_email

from config import basedir, BaseConfig
from sqlalchemy import func
from sendemail import user_auth


@blue_duty.route('/', methods=["GET", "POST"])
def index():
    return render_template('index.html')


# 图片上传接口
@blue_duty.route('/upload', methods=['GET', 'POST', 'OPTIONS'])
@login_required
def upload():
    """UEditor文件上传接口

    config 配置文件
    result 返回结果
    """
    mimetype = 'application/json'
    result = {}
    action = request.args.get('action')

    # 解析JSON格式的配置文件
    with open(os.path.join(basedir, 'app', 'static', 'ueditor', 'php', 'config.json')) as fp:
        try:
            # 删除 `/**/` 之间的注释
            CONFIG = json.loads(re.sub(r'\/\*.*\*\/', '', fp.read()))
        except:
            CONFIG = {}
        if action == 'config':
            # 初始化时，返回配置文件给客户端
            result = CONFIG

        elif action in ('uploadimage', 'uploadfile', 'uploadvideo'):
            # 图片、文件、视频上传
            if action == 'uploadimage':
                # 读取配置文件，确认是上传图片
                fieldName = CONFIG.get('imageFieldName')
                config = {
                    "pathFormat": CONFIG['imagePathFormat'],
                    "maxSize": CONFIG['imageMaxSize'],
                    "allowFiles": CONFIG['imageAllowFiles']
                }
            elif action == 'uploadvideo':
                fieldName = CONFIG.get('videoFieldName')
                config = {
                    "pathFormat": CONFIG['videoPathFormat'],
                    "maxSize": CONFIG['videoMaxSize'],
                    "allowFiles": CONFIG['videoAllowFiles']
                }
            else:
                fieldName = CONFIG.get('fileFieldName')
                config = {
                    "pathFormat": CONFIG['filePathFormat'],
                    "maxSize": CONFIG['fileMaxSize'],
                    "allowFiles": CONFIG['fileAllowFiles']
                }
            # 确认上传图片在请求里
            if fieldName in request.files:
                field = request.files[fieldName]
                # 上传文件在Uploader方法里
                uploader = Uploader(field, config, current_app.static_folder)
                # 返回结果
                result = uploader.getFileInfo()
                # 将图片存入数据库
                filename = uploader.getFileInfo()['filename']
                a = Picture(name=filename)
                db.session.add(a)
                db.session.commit()
            else:
                result['state'] = '上传接口出错'

        elif action in ('uploadscrawl'):
            # 涂鸦上传
            fieldName = CONFIG.get('scrawlFieldName')
            config = {
                "pathFormat": CONFIG.get('scrawlPathFormat'),
                "maxSize": CONFIG.get('scrawlMaxSize'),
                "allowFiles": CONFIG.get('scrawlAllowFiles'),
                "oriName": "scrawl.png"
            }
            if fieldName in request.form:
                field = request.form[fieldName]
                uploader = Uploader(field, config, current_app.static_folder, 'base64')
                result = uploader.getFileInfo()
            else:
                result['state'] = '上传接口出错'

        elif action in ('catchimage'):
            config = {
                "pathFormat": CONFIG['catcherPathFormat'],
                "maxSize": CONFIG['catcherMaxSize'],
                "allowFiles": CONFIG['catcherAllowFiles'],
                "oriName": "remote.png"
            }
            fieldName = CONFIG['catcherFieldName']

            if fieldName in request.form:
                # 这里比较奇怪，远程抓图提交的表单名称不是这个
                source = []
            elif '%s[]' % fieldName in request.form:
                # 而是这个
                source = request.form.getlist('%s[]' % fieldName)

            _list = []
            for imgurl in source:
                uploader = Uploader(imgurl, config, current_app.static_folder, 'remote')
                info = uploader.getFileInfo()
                _list.append({
                    'state': info['state'],
                    'url': info['url'],
                    'original': info['original'],
                    'source': imgurl,
                })

            result['state'] = 'SUCCESS' if len(_list) > 0 else 'ERROR'
            result['list'] = _list

        else:
            result['state'] = '请求地址出错'

        result = json.dumps(result)

        if 'callback' in request.args:
            callback = request.args.get('callback')
            if re.match(r'^[\w_]+$', callback):
                result = '%s(%s)' % (callback, result)
                mimetype = 'application/javascript'
            else:
                result = json.dumps({'state': 'callback参数不合法'})

        res = make_response(result)
        res.mimetype = mimetype
        res.headers['Access-Control-Allow-Origin'] = '*'
        res.headers['Access-Control-Allow-Headers'] = 'X-Requested-With,X_Requested_With'
        return res


@blue_duty.route('/sysmain')
@login_required
def sysmain():
    return render_template('sysmantain.html')


@blue_duty.route('/netsafe')
@login_required
def netsafe():
    return render_template('netsafe.html')


@blue_duty.route('/common')
@login_required
def common():
    return render_template('common.html')


@blue_duty.route('/views')
def views():
    return render_template('view.html')


# 二线数据保存
@blue_duty.route('/datasave', methods=["POST", "GET"])
@login_required
def datasave():
    data = eval(request.get_data())
    if data:
        realdepartid = current_user.group_id
        realdepartname = Group.query.filter_by(id=realdepartid).first().name.encode('utf-8')
        departId = data['departId']
        departAlias = (Group.query.filter_by(id=departId).first().alias).encode('utf-8')
        departName = (data['departName'])
        substance = (data['substance'])
        richTextTime = datetime.strptime(data['richTextTime'], '%Y/%m/%d').date()
        if realdepartid == realdepartid and realdepartname == departName:
            title1 = (data['richTextTime'] + " " + departAlias + "运维日报").decode('utf-8')
            if departName == "OP":
                results = Duty.query.filter_by(title=title1).first()
                if results or (not results and data.get('type') == 'edit'):
                    # 数据的新增和删除
                    if data.get('type') == 'edit' and data.get('dutyId'):
                        richtext = RichText.query.filter_by(duty_id=int(data.get('dutyId')), status=1).first()
                        richtext.content = substance.decode('utf-8')
                        db.session.commit()
                        duty_time = (
                            (Duty.query.filter_by(id=int(data.get('dutyId')), status=1).first()).time).strftime(
                            "%Y/%m/%d")
                        if duty_time != data['richTextTime']:
                            data1 = Duty.query.filter_by(title=title1, status=1).first()
                            if data1:
                                dict1 = {
                                    'code': 1,
                                    'errmessage': '修改的日报时间已存在，请重新选择日报时间'
                                }
                                return jsonify(dict1)
                            else:
                                duty = Duty.query.filter_by(id=int(data.get('dutyId')), status=1).first()
                                duty.time = richTextTime
                                duty.title = title1
                                db.session.commit()
                                richtext = RichText.query.filter_by(duty_id=int(data.get('dutyId')), status=1).first()
                                richtext.time = richTextTime
                                db.session.commit()
                        datalists = data['datalist']
                        if datalists['plus']:
                            for datadict in datalists['plus']:
                                bandwidth = BandWidth(engineroom_id=datadict['room_id'],
                                                      bw=datadict['bw'], time=richTextTime,
                                                      duty_id=int(data.get('dutyId')))
                                db.session.add(bandwidth)
                                db.session.commit()
                        if datalists['delete']:
                            for i in datalists['delete']:
                                bandwidth = BandWidth.query.filter_by(id=i, status=1).first()
                                bandwidth.status = 0
                                db.session.add(bandwidth)
                                db.session.commit()
                        dict1 = {
                            'code': 0,
                            'message': '修改成功',
                            'richTextTime': richTextTime.strftime("%Y/%m/%d")
                        }
                        return jsonify(dict1)
                    else:
                        dict1 = {
                            'code': 1,
                            'errmessage': '今天已经提交过了'
                        }
                        return jsonify(dict1)
                else:
                    # 数据的创建
                    duty = Duty(title=title1, group=departId, time=richTextTime)
                    db.session.add(duty)
                    db.session.commit()
                    substance = substance.decode('utf-8')
                    richtext = RichText(content=substance, duty_id=duty.id, time=richTextTime)
                    db.session.add(richtext)
                    db.session.commit()
                    datalists = data['datalist']
                    if datalists:
                        for datadict in datalists:
                            bandwidth = BandWidth(engineroom_id=datadict['room_id'],
                                                  bw=datadict['bw'], duty_id=duty.id, time=richTextTime)
                            db.session.add(bandwidth)
                            db.session.commit()
                    dict1 = {
                        'code': 0,
                        'message': '保存成功',
                        'dutyId': duty.id,
                        'richTextTime': data['richTextTime']
                    }
                    return jsonify(dict1)
            elif departName == 'SEC':
                results = Duty.query.filter_by(title=title1, status=1).first()
                if results or (not results and data.get('type') == 'edit'):
                    # 数据的新增和删除
                    if data.get('type') == 'edit' and data.get('dutyId'):
                        richtext = RichText.query.filter_by(duty_id=int(data.get('dutyId')), status=1).first()
                        richtext.status = 1
                        richtext.content = substance.decode('utf-8')
                        db.session.commit()
                        duty_time = (
                            (Duty.query.filter_by(id=int(data.get('dutyId')), status=1).first()).time).strftime(
                            "%Y/%m/%d")
                        if duty_time != data['richTextTime']:
                            data1 = Duty.query.filter_by(title=title1, status=1).first()
                            if data1:
                                dict1 = {
                                    'code': 1,
                                    'errmessage': '修改的日报时间已存在，请重新选择日报时间'
                                }
                                return jsonify(dict1)
                            else:
                                duty = Duty.query.filter_by(id=int(data.get('dutyId')), status=1).first()
                                duty.time = richTextTime
                                duty.title = title1
                                db.session.commit()
                                richtext = RichText.query.filter_by(duty_id=int(data.get('dutyId')), status=1).first()
                                richtext.time = richTextTime
                                db.session.commit()
                        datalists = data['datalist']
                        if datalists['plus']:
                            for datadict in datalists['plus']:
                                opevent = OPEvent(title=datadict['title'].decode('utf-8'),
                                                  type=datadict['type'].decode('utf-8'),
                                                  content=datadict['content'].decode('utf-8'),
                                                  time=datetime.strptime(datadict['time'], '%Y/%m/%d %H:%M'),
                                                  duty_id=int(data.get('dutyId')))
                                db.session.add(opevent)
                            db.session.commit()
                        if datalists['delete']:
                            for i in datalists['delete']:
                                opevent = OPEvent.query.filter_by(id=i, status=1).first()
                                opevent.status = 0
                                db.session.commit()
                        dict1 = {
                            'code': 0,
                            'message': '修改成功',
                            'richTextTime': data['richTextTime']
                        }
                        return jsonify(dict1)
                    else:
                        dict1 = {
                            'code': 1,
                            'errmessage': '今天已经提交过了'
                        }
                        return jsonify(dict1)
                else:
                    duty = Duty(title=title1, group=departId, time=richTextTime)
                    db.session.add(duty)
                    db.session.commit()
                    richtext = RichText(content=substance.decode('utf-8'), duty_id=duty.id, time=richTextTime)
                    db.session.add(richtext)
                    db.session.commit()
                    datalists = data['datalist']
                    if datalists:
                        for datadict in datalists:
                            opevent = OPEvent(title=datadict['title'].decode('utf-8'),
                                              type=datadict['type'].decode('utf-8'),
                                              content=datadict['content'].decode('utf-8'),
                                              time=datetime.strptime(datadict['time'], "%Y/%m/%d %H:%M"),
                                              duty_id=duty.id)
                            db.session.add(opevent)
                            db.session.commit()
                    dict1 = {
                        'code': 0,
                        'message': '提交成功',
                        'dutyId': duty.id,
                        'richTextTime': data['richTextTime']
                    }
                    return jsonify(dict1)
            else:
                results = Duty.query.filter_by(title=title1, status=1).first()
                if results or (not results and data.get('type') == 'edit'):
                    # 数据的新增和删除
                    if data.get('type') == 'edit' and data.get('dutyId'):
                        richtext = RichText.query.filter_by(duty_id=int(data.get('dutyId')), status=1).first()
                        richtext.status = 1
                        richtext.content = substance.decode('utf-8')
                        db.session.commit()
                        duty_time = (
                            (Duty.query.filter_by(id=int(data.get('dutyId')), status=1).first()).time).strftime(
                            "%Y/%m/%d")
                        if duty_time != data['richTextTime']:
                            data1 = Duty.query.filter_by(title=title1, status=1).first()
                            if data1:
                                dict1 = {
                                    'code': 1,
                                    'errmessage': '修改的日报时间已存在，请重新选择日报时间'
                                }
                                return jsonify(dict1)
                            else:
                                duty = Duty.query.filter_by(id=int(data.get('dutyId')), status=1).first()
                                duty.time = richTextTime
                                duty.title = title1
                                db.session.commit()
                                richtext = RichText.query.filter_by(duty_id=int(data.get('dutyId')), status=1).first()
                                richtext.time = richTextTime
                                db.session.commit()
                        dict1 = {
                            'code': 0,
                            'message': '修改成功',
                            'richTextTime': richTextTime.strftime("%Y/%m/%d")
                        }
                        return jsonify(dict1)
                    else:
                        dict1 = {
                            'code': 1,
                            'errmessage': '今天已经提交过了'
                        }
                        return jsonify(dict1)
                else:
                    duty = Duty(title=title1, group=departId, time=richTextTime)
                    db.session.add(duty)
                    db.session.commit()
                    richtext = RichText(content=substance.decode('utf8'), duty_id=duty.id, time=richTextTime)
                    db.session.add(richtext)
                    db.session.commit()
                    dict1 = {
                        'code': 0,
                        'message': '提交成功',
                        'dutyId': duty.id,
                        'richTextTime': data['richTextTime']
                    }
                    return jsonify(dict1)
        else:
            dict1 = {
                'code': 1,
                'errmessage': '参数已接收但和数据库不匹配'
            }
            return jsonify(dict1)
    else:
        dict1 = {
            'code': 1,
            'errmessage': '后端未获取到你提交的数据'
        }
        return jsonify(dict1)


# 二线和三线数据提交后预览
@blue_duty.route('/datashow', methods=["GET", "POST"])
def datashow():
    data = request.args.to_dict()
    if data:
        dutyId = int(data['dutyId'])
        departId = int(data['departId'])
        level = int(data['level'])
        name = Group.query.filter_by(id=departId, status=1).first().name
        dict2 = {}
        tableList = []
        dict2['departId'] = departId
        dict2['dutyId'] = dutyId
        if name == 'OP':
            richText = (RichText.query.filter_by(duty_id=dutyId, status=1).first()).content
            richTextTime = ((RichText.query.filter_by(duty_id=dutyId, status=1).first()).time).strftime("%Y/%m/%d")
            dict2['richText'] = richText
            dict2['richTextTime'] = richTextTime
            datalist = BandWidth.query.filter_by(duty_id=dutyId, status=1).all()
            if datalist:
                for data in datalist:
                    dict1 = {}
                    dict1['band_id'] = data.id
                    dict1['idc'] = EngineRoom.query.filter_by(id=data.engineroom_id, status=1).first().alias
                    dict1['bw'] = data.bw
                    dict1['room_id'] = data.engineroom_id
                    tableList.append(dict1)
            dict2['tableList'] = tableList
            return jsonify(dict2)
        elif name == 'SEC':
            richText = RichText.query.filter_by(duty_id=dutyId, status=1).first().content
            richTextTime = (RichText.query.filter_by(duty_id=dutyId, status=1).first().time).strftime("%Y/%m/%d")
            dict2['richText'] = richText
            dict2['richTextTime'] = richTextTime
            datalist = OPEvent.query.filter_by(duty_id=dutyId, status=1)
            if datalist:
                for data in datalist:
                    dict1 = {}
                    dict1['event_id'] = data.id
                    dict1['title'] = data.title
                    dict1['type'] = data.type
                    dict1['content'] = data.content
                    dict1['ctime'] = (data.time).strftime("%Y/%m/%d %H:%M")
                    tableList.append(dict1)
            dict2['tableList'] = tableList
            return jsonify(dict2)
        else:
            if level == 3:
                dict1 = {}
                dict1['dutyId'] = dutyId
                dict1['departId'] = departId
                dict1['onDutyThirdName'] = DailyInfo.query.filter_by(duty_id=dutyId, status=1).first().line3
                dict1['onDutyForthName'] = DailyInfo.query.filter_by(duty_id=dutyId, status=1).first().line4
                time1 = (Duty.query.filter_by(id=dutyId, status=1).first().time).strftime("%Y/%m/%d")
                dict1['richTextTime'] = time1
                datalist = OPEvent.query.filter_by(duty_id=dutyId, status=1).all()
                list1 = []
                if datalist:
                    for data in datalist:
                        dict2 = {}
                        dict2['brokeTime'] = (data.time).strftime("%Y/%m/%d %H:%M")
                        dict2['brokeContent'] = data.content
                        dict2['eventId'] = data.id
                        dict2['brokeDeal'] = data.response
                        list1.append(dict2)
                    dict1['tableList'] = list1
                    return jsonify(dict1)
                else:
                    dict1['tableList'] = list1
                    return jsonify(dict1)
            else:
                dict2 = {}
                tableList = []
                richText = (RichText.query.filter_by(duty_id=dutyId, status=1).first()).content
                if richText:
                    richTextTime = ((RichText.query.filter_by(duty_id=dutyId, status=1).first()).time).strftime(
                        "%Y/%m/%d")
                    dict2['richTextTime'] = richTextTime
                    dict2['departId'] = departId
                    dict2['dutyId'] = dutyId
                    dict2['richText'] = richText
                    dict2['tableList'] = tableList
                    return jsonify(dict2)
    else:
        dict1 = {
            'code': 1,
            'errmessage': '传入的数据为空'
        }
        return jsonify(dict1)


@blue_duty.route('/dutydatalist', methods=['GET'])
def dutydata_list():
    """
    二线报告列表数据、三线报告列表数据、当前用户的值班报告列表数据

    ### Method
    - GET
    
    ### Request
    - Param

        | 变量名 | 值 | 说明 |
        | :- | :- | :- |
        | currentuser | 0/1 | 是否显示当前用户的报告列表 |
        | level       | 2/3 | 二线或者三线; 如果currentuser为1, 此参数被忽略 |

    ### Respone
    - Type: json
    - e.g.
    ```
    {
        "ret": int(1)/int(0),
        "data": [
            {
                "departAlias": u"系统运维部",
                "departId": int(1),
                "departName": "OPS",
                "dutyId": int(12),
                "dutyTitle": u"2018/04/12 系统运维部 二线值班报告",
                "time": "2018/04/12"
            }
        ],
        "level" : int(2)/int(3),
        "msg": [
            u"查询成功",
            u"参数错误"
        ]
    }
    ```
    
    ### Note

    """

    result = {"ret": 0, "data": [], "msg": []}
    try:
        if int(request.args.get('currentuser', 0)):
            if current_user.is_authenticated:
                query_data = current_user.the_group.dutys.order_by(Duty.ctime.desc()).all()
            else:
                raise AttributeError()
        else:
            level = int(request.args.get('level'))
            result['level'] = level
            query_data = Duty.query.filter(Duty.level == level).order_by(Duty.ctime.desc()).all()
            #
    except:
        result['msg'].append(u"参数错误")
        return jsonify(result)
    #

    for d in query_data:
        temp = {}
        temp['dutyId'] = d.id
        temp['dutyTitle'] = d.title
        temp['time'] = d.time.strftime("%Y/%m/%d")
        temp['departId'] = d.the_group.id
        temp['departAlias'] = d.the_group.alias
        temp['departName'] = Group.query.filter_by(id=d.group).first().name
        result['data'].append(temp)
    #
    result['msg'].append(u"查询成功")
    result['ret'] = 1
    return jsonify(result)


@blue_duty.route('/manage', methods=["GET", "POST"])
@login_required
def manage():
    if current_user.the_group.name == 'ADMIN':
        return render_template('tempManage.html')
    else:
        return abort(403)


##二线
@blue_duty.route('/secline', methods=["GET"])
def secline():
    return render_template('secline.html')


##我的二线日报
@blue_duty.route('/mySecondlist', methods=["GET"])
def mySecline():
    return render_template('mysecline.html')


##三线
@blue_duty.route('/thirdline', methods=["GET"])
def thirdline():
    return render_template('thirdline.html')


##我的三线日报
@blue_duty.route('/myThirdlist', methods=["GET"])
def myThirdline():
    return render_template('myThirdline.html')


##三线创建
@blue_duty.route('/createThirdline', methods=["GET"])
@login_required
def createThirdline():
    return render_template('thirdForm.html')


##三线预览
@blue_duty.route('/viewThird', methods=["GET"])
def viewThird():
    return render_template('viewThird.html')


# 部门下拉菜单接口
@blue_duty.route('/groups', methods=["GET"])
def groups():
    """
    ##### request
    None 或者
    {'viewDetail':int(x)}
    ##### response
    ```
    [{'departId':int(12),
      'departName':u'xxx',
      'departAlias':u'yyy',
     },
    ]
    ```
    ##### note
    若没登录，返回部分部门信息；
    若登录：若没参数，返回当前部门信息，若有参数==1，返回所有；若参数==0，返回部分。
    """
    data = request.args
    viewDetail = data.get('viewDetail')
    if current_user.is_authenticated:
        # 登录
        if viewDetail:
            if int(viewDetail) == 1:

                # 返回所有（除了三线），模板使用

                groups_c = Group.query.filter(Group.name != 'LEVEL3').order_by(Group.alias).all()
                list = []
                for group in groups_c:
                    dict = {}
                    dict['departId'] = group.id
                    dict['departName'] = group.name
                    dict['departAlias'] = group.alias
                    list.append(dict)
                return jsonify(list)
            elif int(viewDetail) == 0:
                # 返回部分，三线使用
                groups_c = Group.query.filter(Group.name != 'ADMIN').order_by(Group.alias).all()
                list = []
                for group in groups_c:
                    dict = {}
                    dict['departId'] = group.id
                    dict['departName'] = group.name
                    dict['departAlias'] = group.alias
                    list.append(dict)
                return jsonify(list)
        else:
            # 不传参，返回当前
            group_id = current_user.group_id
            group_name = current_user.the_group.name
            group_alias = current_user.the_group.alias
            list = []
            dict1 = {}
            dict1['departId'] = group_id
            dict1['departName'] = group_name
            dict1['departAlias'] = group_alias
            list.append(dict1)
            return jsonify(list)
    else:
        # 没登录，返回部分，供三线使用
        groups_c = Group.query.filter(Group.name != 'ADMIN').order_by(Group.alias).all()
        list = []
        for group in groups_c:
            dict = {}
            dict['departId'] = group.id
            dict['departName'] = group.name
            dict['departAlias'] = group.alias
            list.append(dict)
        return jsonify(list)


# 模板数据查询及帮助手册
@blue_duty.route('/gettemplate', methods=['GET', 'POST'])
def gettemplate():
    """
    ##### request
    {'departId':int(12)}
    ##### response
    ```
    {
     "code": 0,
     "data": {'tempText':u'xxx'},
    }
    ```
    ##### note
    有模板内容，渲染出来，只有系统管理员和自己才能查看自己组的模板
    """
    # 接收参数
    data1 = request.args
    group_id = data1.get('departId')
    group_name = data1.get('departName')
    # 验证参数
    if group_name == 'ADMIN':
        # 获取帮助手册
        gr_id = Group.query.filter(Group.name == 'ADMIN').first().id
        try:
            temp_content = TempText.query.filter(TempText.group_id == gr_id).first().content
            dict1 = {
                'code': 0,
                'data': {
                    'tempText': temp_content
                }
            }
            return jsonify(dict1)
        except:
            dict1 = {
                'code': 0,
                'data': {
                    'tempText': ''
                }
            }
            return jsonify(dict1)
    data = {}
    if current_user.is_authenticated:
        # 查询当前用户所在的部门
        g_id = unicode(current_user.group_id)
        g_name = current_user.the_group.name
        if group_id != g_id and g_name != 'ADMIN':
            dict1 = {
                'code': 1,
                'errmessage': '用户和部门不匹配'
            }
            return jsonify(dict1)
        try:
            # 有模板内容，渲染出来
            temp_content = TempText.query.filter(TempText.group_id == group_id).first().content
            data['tempText'] = temp_content
            dict = {
                'code': 0,
                'data': data
            }
            return jsonify(dict)
        except:
            # 没有模板内容
            data['tempText'] = ''
            dict = {
                'code': 0,
                'data': data
            }
            return jsonify(dict)
    else:
        dict1 = {
            'code': 1,
            'errmessage': '没有登录'
        }
        return jsonify(dict1)


# 模板数据保存
@blue_duty.route('/edittemplate', methods=["POST"])
@login_required
def edittemplate():
    """
    ##### request
    {'departId':int(12),
     'tempText':u'xxx',
    }
    ##### response
    ```
    {
     'code': 0,
     'message': '保存成功',
    }
    ```
    ##### note
    模板的增加，修改及删除，根据传入temp_text的不同加以操作：
    若temp_text为空，删除模板；若原库中有模板内容，则修改；若没有，则增加。
    只有系统管理员和自己能对属于自己组的模板进行操作。
    """
    # 获取参数
    data = request.form
    group_id = data.get('departId')
    temp_text = data.get('tempText')
    # 查询当前用户所在的部门
    g_id = unicode(current_user.group_id)
    g_name = current_user.the_group.name
    if group_id != g_id and g_name != 'ADMIN':
        dict1 = {
            'code': 1,
            'errmessage': '用户和部门不匹配'
        }
        return jsonify(dict1)
    if not temp_text:
        # 是将部门对应的模板内容改为空
        te = TempText.query.filter_by(group_id=int(group_id)).first()
        db.session.delete(te)
        db.session.commit()
        dict = {
            'code': 0,
            'message': '保存成功',
        }
        return jsonify(dict)
    # 是否能获取到模板内容
    try:
        # 修改模板
        te = TempText.query.filter_by(group_id=int(group_id)).first()
        te.content = temp_text
        db.session.add(te)
        db.session.commit()
    except:
        # 增加模板内容
        title = Group.query.filter_by(id=int(group_id)).first().alias
        te = TempText(group_id=int(group_id), content=temp_text, title=title)
        db.session.add(te)
        db.session.commit()
    dict = {
        'code': 0,
        'message': '保存成功',
    }
    return jsonify(dict)


# 三线数据保存
@blue_duty.route('/thirddatasave', methods=["POST"])
@login_required
def thirddatasave():
    data = request.json
    if data:
        departId = int(data.get('departId'))
        realdepartid = current_user.group_id
        dutyTime = datetime.strptime(data.get('richTextTime'), '%Y/%m/%d').date()
        if departId == realdepartid:
            onDutyThirdName = data.get('onDutyThirdname')
            onDutyForthName = data.get('onDutyForthname')
            title1 = (data.get('richTextTime').encode('utf-8') + " " + "CNTV大运维交接").decode('utf-8')
            results = Duty.query.filter_by(title=title1, status=1).first()
            if results or (not results and data.get('type') == 'edit'):
                # 数据的新增和删除
                if data.get('type') == 'edit' and data.get('dutyId'):
                    dailyinfo = DailyInfo.query.filter_by(duty_id=int(data.get('dutyId')), status=1).first()
                    dailyinfo.line3 = onDutyThirdName
                    dailyinfo.line4 = onDutyForthName
                    dailyinfo.duty_id = int(data.get('dutyId'))
                    db.session.commit()
                    duty_time = ((Duty.query.filter_by(id=int(data.get('dutyId')), status=1).first()).time).strftime(
                        "%Y/%m/%d")
                    if duty_time != data.get('richTextTime').encode('utf-8'):
                        data1 = Duty.query.filter_by(title=title1, status=1).first()
                        if data1:
                            dict1 = {
                                'code': 1,
                                'errmessage': '修改的日报时间已存在，请重新选择日报时间'
                            }
                            return jsonify(dict1)
                        else:
                            duty = Duty.query.filter_by(id=int(data.get('dutyId')), status=1).first()
                            duty.time = dutyTime
                            duty.title = title1
                            db.session.commit()
                            dailyinfo = DailyInfo.query.filter_by(duty_id=int(data.get('dutyId')), status=1).first()
                            dailyinfo.time = dutyTime
                            db.session.commit()
                    datalists = data.get('datalist')
                    if datalists.get('plus'):
                        for datadict in datalists.get('plus'):
                            opevent = OPEvent(title='LINE3EVENT',
                                              type='BREAKDOWN',
                                              level=3,
                                              duty_id=int(data.get('dutyId')),
                                              content=datadict['brokeContent'],
                                              response=datadict.get('brokeDeal'),
                                              time=datetime.strptime(datadict.get('brokeTime').encode('utf-8'),
                                                                     '%Y/%m/%d %H:%M'))
                            db.session.add(opevent)
                            db.session.commit()
                    if datalists.get('delete'):
                        for i in datalists.get('delete'):
                            opevent = OPEvent.query.filter_by(id=i, status=1).first()
                            opevent.status = 0
                            db.session.commit()
                    dict1 = {
                        'code': 0,
                        'message': '修改成功',
                        'richTextTime': data['richTextTime']
                    }
                    return jsonify(dict1)
                else:
                    dict1 = {
                        'code': 1,
                        'errmessage': '今天已经提交过了'
                    }
                    return jsonify(dict1)
            else:
                duty = Duty(title=title1, group=departId, level=3, time=dutyTime)
                db.session.add(duty)
                db.session.commit()
                dailyinfo = DailyInfo(line3=onDutyThirdName, line4=onDutyForthName,
                                      duty_id=duty.id, time=dutyTime)
                db.session.add(dailyinfo)
                db.session.commit()
                datalists = json.loads(data.get("datalist").encode('utf-8'))
                if datalists:
                    for data1 in datalists:
                        if data1.get('brokeTime'):
                            time1 = datetime.strptime(data1.get('brokeTime'), '%Y/%m/%d %H:%M')
                        else:
                            time1 = datetime.now()
                        content = data1.get('brokeContent')
                        response = data1.get('brokeDeal')
                        opevent = OPEvent(title='LINE3EVENT', type='BREAKDOWN', level=3, duty_id=duty.id,
                                          content=content,
                                          response=response, time=time1)
                        db.session.add(opevent)
                        db.session.commit()
                dict1 = {
                    'code': 0,
                    'message': '提交成功',
                    'dutyId': duty.id,
                    'dutyTime': dutyTime
                }
                return jsonify(dict1)
        else:
            dict1 = {
                'code': 1,
                'errmessage': '传入的数据和数据库中的不一致'
            }
            return jsonify(dict1)
    else:
        dict1 = {
            'code': 1,
            'errmessage': '你提交的数据为空，暂无法保存'
        }
        return jsonify(dict1)


# 三线下的二线数据展示
@blue_duty.route('/threeshowtwo', methods=['GET'])
def threeshowtwo():
    """
    ##### request
    {'departId':int(12),
     'departName':u'xxx',
     'time':u'2018/04/09'
    }
    ##### response
    ```
    {'dutyId':int(12),
     'departId':int(12),
     'richText':u'xxx',
     'tableList':['event':u'xxx',
                  'type':u'xxx',
                  'content':u'xxx',
                  'time':u'时间格式',
                 ]
    }
    ```
    ##### note
    根据接收到的部门ID及时间，确定唯一的一条日报信息，返回日报里的所有信息，
    注意两个特殊部门：SEC及OP，返回tableList相对应表中的字段值        
    """
    data = request.args
    group_id = data.get('departId')
    group_name = data.get('departName')
    duty_time = data.get('time')
    if not all([group_id, group_name, duty_time]):
        dict1 = {
            'code': 1,
            'errmessage': '参数获取不完整'
        }
        return jsonify(dict1)
    duty_time1 = duty_time.replace("/", "-")
    # 查询此部门，此时间点的日报id,富文本内容
    try:
        duty_id = Duty.query.filter(Duty.group == group_id, Duty.time.startswith(duty_time1),
                                    Duty.status == 1).first().id
        try:
            rich_content = RichText.query.filter_by(duty_id=duty_id, status=1).first().content
            table_list = []
            if group_name == 'SEC':
                # 网络安全部的返回信息
                opevent = OPEvent.query.filter_by(duty_id=duty_id, status=1).all()
                if not opevent:
                    table_list = []
                    dict = {
                        'dutyId': duty_id,
                        'departId': group_id,
                        'richText': rich_content,
                        'tableList': table_list,
                    }
                    return jsonify(dict)
                list = []
                for ope in opevent:
                    dict1 = {}
                    dict1['event'] = ope.title
                    dict1['type'] = ope.type
                    dict1['content'] = ope.content
                    dict1['time'] = ope.time.strftime("%Y/%m/%d %H:%M")
                    list.append(dict1)
                    table_list = list
            elif group_name == 'OP':
                # 系统运维部的返回信息
                bandwidth = BandWidth.query.filter_by(duty_id=duty_id, status=1).all()
                if not bandwidth:
                    table_list = []
                    dict = {
                        'dutyId': duty_id,
                        'departId': group_id,
                        'richText': rich_content,
                        'tableList': table_list,
                    }
                    return jsonify(dict)
                list = []
                for band in bandwidth:
                    dict1 = {}
                    dict1['idc'] = band.the_engineroom.alias
                    dict1['bw'] = band.bw
                    list.append(dict1)
                    table_list = list
            dict = {
                'dutyId': duty_id,
                'departId': group_id,
                'richText': rich_content,
                'tableList': table_list,
            }
            return jsonify(dict)
        except:
            rich_content = ''
            table_list = []
            dict = {
                'dutyId': duty_id,
                'departId': group_id,
                'richText': rich_content,
                'tableList': table_list,
            }
            return jsonify(dict)
    except:
        duty_id = ''
        rich_content = ''
        table_list = []
        dict = {
            'dutyId': duty_id,
            'departId': group_id,
            'richText': rich_content,
            'tableList': table_list,
        }
        return jsonify(dict)


# group列表接口
@blue_duty.route('/currentgroup', methods=["GET"])
@login_required
def currentgroup():
    """
    ##### request
    none
    ##### response
    ```
    [
    {'group_id':int(12),
    'group_name':u'xxx',
    'group_alias':u'yyy'
    },
    ]
    ```    
    ##### note
    """
    group_id = current_user.group_id
    group_name = current_user.the_group.name
    group_alias = current_user.the_group.alias
    dict1 = {}
    dict1['group_id'] = group_id
    dict1['group_name'] = group_name
    dict1['group_alias'] = group_alias
    return jsonify(dict1)


# 机房信息
@blue_duty.route('/engineroom', methods=['GET'])
def engineroom():
    """
    ##### request
    none
    ##### response
    ```
    [
    {'room_id':int(12),
    'room_name':u'xxx',
    'room_alias':u'yyy'
    },
    ]
    ```    
    ##### note
    """
    enginerooms = EngineRoom.query.all()
    list = []
    for room in enginerooms:
        dict = {}
        dict['room_id'] = room.id
        dict['room_name'] = room.name
        dict['room_alias'] = room.alias
        list.append(dict)
    return jsonify(list)


##帮助手册
@blue_duty.route("/gethelp", methods=["GET"])
def gethelp():
    return render_template("help.html")


##生成报告
@blue_duty.route("/produceReport", methods=["GET"])
@login_required
def produceReport():
    if current_user.the_group.name != 'LEVEL3':
        return abort(403)
    return render_template("report.html")


# 邮件预览
@blue_duty.route('/dutyInfo', methods=['GET'])
def emailInfo():
    # 接收参数
    result = {'code': 0, 'data': {}}
    data = request.args
    dutyId = data.get('dutyId')
    level = data.get('level')
    # 校验参数
    if not all([dutyId, level]):
        error = {
            'code': 1,
            'errmessage': u'参数不完整',
        }
        return jsonify(error)
    duty = Duty.query.filter(Duty.id == dutyId, Duty.status == 1).first()
    if not duty:
        error = {
            'code': 1,
            'errmessage': u'不存在的dutyId',
        }
        return jsonify(error)
    # 1 日报id
    result['data']['dutyId'] = dutyId
    # 2 日报时间
    dutyTime = duty.time.strftime('%Y/%m/%d')
    result['data']['dutyTime'] = dutyTime
    duty_Time = duty.time
    # 3 ope 异常事件
    opEvent = OPEvent.query.filter(OPEvent.status == 1, OPEvent.duty_id == dutyId).all()
    dataList = []
    if opEvent:
        for ope in opEvent:
            dict1 = {}
            dict1['brokeContent'] = ope.content
            dict1['brokeDeal'] = ope.response
            dict1['brokeTime'] = ope.time.strftime('%Y/%m/%d %H:%M')
            dict1['eventId'] = ope.id
            dataList.append(dict1)
    else:
        dict2 = {}
        dict2['brokeContent'] = ''
        dict2['brokeDeal'] = ''
        dict2['brokeTime'] = ''
        dict2['eventId'] = ''
        dataList.append(dict2)
    result['data']['dataList'] = dataList
    # 4 部门级别
    result['data']['level'] = level
    # 5 值班信息
    onDutyThirdName = DailyInfo.query.filter(DailyInfo.time == duty_Time, DailyInfo.status == 1).first().line3
    onDutyForthName = DailyInfo.query.filter(DailyInfo.time == duty_Time, DailyInfo.status == 1).first().line4
    result['data']['onDutyThirdName'] = onDutyThirdName
    result['data']['onDutyForthName'] = onDutyForthName
    # 6 二线日报列表
    secondList = []
    # 6.1 此时间点二线日报列表
    duty_list = Duty.query.filter(Duty.level == 2, Duty.time == duty_Time, Duty.status == 1).all()
    if duty_list:
        for duty in duty_list:
            dict3 = {}
            dict3['dutyId'] = duty.id
            dict3['dutyTime'] = dutyTime
            dict3['richText'] = duty.rt.content
            dict3['departId'] = duty.group
            dict3['departAlias'] = duty.the_group.alias
            dict3['departName'] = duty.the_group.name
            tableList = []
            if dict3['departName'] == 'SEC':
                # 返回网络安全部的信息
                ope_vents = OPEvent.query.filter(OPEvent.duty_id == dict3['dutyId'], OPEvent.status == 1).all()
                if ope_vents:
                    for ope in ope_vents:
                        dict4 = {}
                        dict4['event'] = ope.title
                        dict4['type'] = ope.type
                        dict4['content'] = ope.content
                        dict4['time'] = ope.time.strftime("%Y/%m/%d %H:%M")
                        tableList.append(dict4)
            elif dict3['departName'] == 'OP':
                # 返回系统运维部的信息
                bandwidth = BandWidth.query.filter(BandWidth.duty_id == dict3['dutyId'], OPEvent.status == 1,
                                                   BandWidth.time.startswith(unicode(duty_Time))).all()
                if bandwidth:
                    for band in bandwidth:
                        dict5 = {}
                        dict5['idc'] = band.the_engineroom.alias
                        dict5['bw'] = band.bw
                        tableList.append(dict5)
            dict3['tableList'] = tableList
            secondList.append(dict3)
        # 6.2 此日报时间点没有日报的其他部门
        list1 = []
        for group_id in duty_list:
            g_id = group_id.group
            list1.append(g_id)
        groups = Group.query.filter(Group.status == 1, Group.name != 'ADMIN', Group.name != 'LEVEL3',
                                    ~Group.id.in_(list1)).all()
        for group in groups:
            dict6 = {}
            dict6['departAlias'] = group.alias
            dict6['departId'] = group.id
            dict6['departName'] = group.name
            dict6['dutyId'] = ''
            dict6['dutyTime'] = dutyTime
            dict6['richText'] = ''
            dict6['tableList'] = []
            secondList.append(dict6)
        result['data']['secondList'] = secondList
        return jsonify(result)
    else:
        # 7 返回所有的部门日报信息
        groups = Group.query.filter(Group.name != 'LEVEL3', Group.name != 'ADMIN', Group.status == 1).all()
        for group in groups:
            dict7 = {}
            dict7['departAlias'] = group.alias
            dict7['departId'] = group.id
            dict7['departName'] = group.name
            dict7['dutyId'] = ''
            dict7['dutyTime'] = dutyTime
            dict7['richText'] = ''
            dict7['tableList'] = []
            secondList.append(dict7)
        result['data']['secondList'] = secondList
        # 返回数据
        return jsonify(result)


# 发送邮件
@blue_duty.route('/sendEmail', methods=['GET', 'POST'])
def sendEmail():
    data = request.json
    list1 = data.get('imgList')
    ceshi = data.get('emailTemp')
    str2 = data.get('emailTitle').encode('utf-8').replace('&nbsp;', ' ')
    title = ' '.join(str2.split())
    subject = (BaseConfig.MAIL_PERFIX + '  ' + title).decode('utf-8')
    addressee = Email.query.filter_by(name='sanxian').first()
    if addressee:
        addressee = addressee.address
        uid = uuid4().get_hex()
        emailstatus = EmailStatus(status=u'邮件创建成功', uniquenum=uid)
        db.session.add(emailstatus)
        db.session.commit()
        send_email(uid, addressee, subject, ceshi, imgs=list1, )
        return jsonify({"code": 0, "uid": uid})
    else:
        return jsonify({"code": 1, "errmessage": '发送失败，未配置收件人'})


# 判断邮件是否发送成功
@blue_duty.route('/checkEmail', methods=['GET', 'POST'])
def checkEmail():
    data = request.json
    uid = data.get('uid')
    status = EmailStatus.query.filter_by(uniquenum=uid).first().status
    return jsonify({"status": status})


# 数据统计v1
@blue_duty.route('/dashboard/v1', methods=['GET'])
def dashboard1():
    result = {'code': 0, 'data': {}, 'message': u'查询成功'}
    data = request.args
    # 参数校验
    if not data:
        error = {
            'code': -1,
            'errmessage': u'请传入参数',
        }
        return jsonify(error)
    band_width = data.get('bandWidth')
    ope_vent = data.get('opEvent')
    level_three = data.get('levelThree')
    # 传入3个参数值为零
    if band_width and ope_vent and level_three:
        if int(band_width) == 0 and int(ope_vent) == 0 and int(level_three) == 0:
            result['message'] = u'没有数据'
            return jsonify(result)
    today = datetime.today().date()
    # 1 返回7天带宽值数据
    if band_width and int(band_width) == 1:
        # 1.1 7天日期
        seven_list = []
        six_ago = today - timedelta(days=7)
        seven_list.append(six_ago)
        five_ago = today - timedelta(days=6)
        seven_list.append(five_ago)
        four_ago = today - timedelta(days=5)
        seven_list.append(four_ago)
        three_ago = today - timedelta(days=4)
        seven_list.append(three_ago)
        two_ago = today - timedelta(days=3)
        seven_list.append(two_ago)
        yesteray = today - timedelta(days=2)
        seven_list.append(yesteray)
        yesterday1 = today - timedelta(days=1)
        seven_list.append(yesterday1)
        bandWidth = []
        for i in range(7):
            dict1 = {}
            dict1['time'] = seven_list[i].strftime('%Y/%m/%d')
            idcList = []
            # 1.2 有记录的机房带宽值
            bans = BandWidth.query.filter(BandWidth.status == 1, BandWidth.time == seven_list[i]).all()
            roomid_list = []
            if bans:
                for ba in bans:
                    dict2 = {}
                    dict2['bw'] = ba.bw
                    dict2['idc'] = ba.the_engineroom.alias
                    dict2['id'] = ba.the_engineroom.id
                    roomid_list.append(ba.the_engineroom.id)
                    idcList.append(dict2)
            # 1.3 漏填某个机房数据或者没有数据
            rooms = EngineRoom.query.filter(~EngineRoom.id.in_(roomid_list)).all()
            for room in rooms:
                dict3 = {}
                dict3['bw'] = 0
                dict3['idc'] = room.alias
                dict3['id'] = room.id
                idcList.append(dict3)
            dict1['idcList'] = idcList
            bandWidth.append(dict1)
        result['data']['bandWidth'] = bandWidth
    # 2 返回网络事件种类比例
    month_first = datetime(today.year, today.month, 1, 0, 0, 0)
    now = datetime(today.year, today.month, today.day, 23, 59, 59)
    if ope_vent and int(ope_vent) == 1:
        opEvent = []
        opes = db.session.query(OPEvent.type, func.count(OPEvent.type)).filter(OPEvent.status == 1, OPEvent.level == 2,
                                                                               OPEvent.time.between(month_first,now)).\
                                                                                group_by(OPEvent.type).all()
        # 有数据
        if opes:
            for op in opes:
                dict4 = {}
                dict4['type'] = op[0]
                dict4['number'] = op[1]
                opEvent.append(dict4)
        else:
            pass
        result['data']['opEvent'] = opEvent
    # 3 三线事件数量
    if level_three and int(level_three) == 1:
        levelThree = []
        # 3.1 日期列表
        month_first1 = datetime(today.year, today.month, 1).date()
        day_now = today.strftime('%Y-%m-%d')
        day_list = []
        i = 0
        while month_first1.strftime('%Y-%m-%d') <= day_now:
            day_str = month_first1.strftime('%Y-%m-%d')
            day_list.append(day_str)
            month_first1 += timedelta(days=1)
            i += 1
            continue
        # 3.2 按日期取值
        for t in range(i):
            dict5 = {}
            dict5['time'] = day_list[t].replace('-', '/')
            levels = OPEvent.query.filter(OPEvent.status == 1, OPEvent.level == 3,
                                          OPEvent.time.startswith(day_list[t])).count()
            dict5['number'] = levels if levels != 0 else 0
            levelThree.append(dict5)
        result['data']['levelThree'] = levelThree
    return jsonify(result)


# 数据统计v2
@blue_duty.route('/dashboard/v2', methods=['GET'])
def dashboard2():
    result = {'code': 0, 'data': {}, 'message': u'查询成功'}
    data = request.args
    # 参数校验
    if not data:
        error = {
            'code': -1,
            'errmessage': u'请传入参数',
        }
        return jsonify(error)
    band_width = data.get('bandWidth')
    ope_vent = data.get('opEvent')
    level_three = data.get('levelThree')
    # 传入3个参数值为零
    if band_width and ope_vent and level_three:
        if int(band_width) == 0 and int(ope_vent) == 0 and int(level_three) == 0:
            result['message'] = u'没有数据'
            return jsonify(result)
    # 1 6个机房7天带宽值数据
    today = datetime.today().date()
    if band_width and int(band_width) == 1:
        bandWidth = {}
        # 1.1 7天日期列表
        timeList = []
        i = 7
        while i >= 1:
            day_next = (today - timedelta(days=i)).strftime('%Y/%m/%d')
            timeList.append(day_next)
            i -= 1
            continue
        seven_day = today - timedelta(days=7)
        yesterday = today - timedelta(days=1)
        bandWidth['timeList'] = timeList
        # 1.2 6个机房id对应机房名
        idcList = {}
        rooms = EngineRoom.query.filter(EngineRoom.status == 1).all()
        for room in rooms:
            idcList[room.id] = room.alias
        bandWidth['idcList'] = idcList
        # 1.3 6个机房id对应有数据的带宽值{}
        bandData = {}
        # 有记录的带宽值
        bws = BandWidth.query.filter(BandWidth.status == 1, BandWidth.time.between(seven_day, yesterday)).all()
        if bws:
            for bw in bws:
                dict1 = {}
                if bw.engineroom_id in bandData.keys():
                    # 追加记录
                    bandData[bw.engineroom_id][bw.time.strftime('%Y/%m/%d')] = bw.bw
                else:
                    bandData[bw.engineroom_id]= dict1
                    dict1[bw.time.strftime('%Y/%m/%d')] = bw.bw
        # 无记录的机房id
        room_ids1 = idcList.keys()
        room_ids2 = bandData.keys()
        room_ids3 = list(set(room_ids1) ^ set(room_ids2))
        for i in room_ids3:
            bandData[i] = {}
        bandWidth['bandData'] = bandData
        result['data']['bandWidth'] = bandWidth
    # 2 网络事件种类比例
    month_first = datetime(today.year, today.month, 1, 0, 0, 0)
    now = datetime(today.year, today.month, today.day, 23, 59, 59)
    if ope_vent and int(ope_vent) == 1:
        opEvent = []
        opes = db.session.query(OPEvent.type, func.count(OPEvent.type)).filter(OPEvent.level == 2, OPEvent.status == 1,
                                                                               OPEvent.time.between(month_first, now)).\
                                                                                group_by(OPEvent.type).all()
        if opes:
            for op in opes:
                dict2 = {}
                dict2['type'] = op[0]
                dict2['number'] = op[1]
                opEvent.append(dict2)
        result['data']['opEvent'] = opEvent
    # 3 三线事件数量
    if level_three and int(level_three) == 1:
        levelThree = {}
        # 3.1 日期列表
        month_first1 = datetime(today.year, today.month, 1).date()
        month_first2 = datetime(today.year, today.month, 1)
        day_now = today.strftime('%Y-%m-%d')
        timeList = []
        while month_first1.strftime('%Y-%m-%d') <= day_now:
            day_str = month_first1.strftime('%Y/%m/%d')
            timeList.append(day_str)
            month_first1 += timedelta(days=1)
            continue
        levelThree['timeList'] = timeList
        # 本月三线事件数量
        data = {}
        opes = OPEvent.query.filter(OPEvent.status == 1, OPEvent.level == 3,
                                    OPEvent.time.between(month_first2, now)).all()
        if opes:
            for ope in opes:
                # 日期重复存在，则数量+1，否则为1
                if ope.time.strftime('%Y/%m/%d') in data.keys():
                    data[ope.time.strftime('%Y/%m/%d')] += 1
                else:
                    data[ope.time.strftime('%Y/%m/%d')] = 1
        levelThree['data'] = data
        result['data']['levelThree'] = levelThree
    return jsonify(result)


# 状态监控
@blue_duty.route('/statusMonitor', methods=['GET'])
def statusMonitor():
    time_now = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
    result = {'TIME': time_now, 'DB': False, 'SMTP': False}
    code = 402
    users = User.query.count()
    smtps = user_auth()
    if users < 1:
        pass
    else:
        result['DB'] = True
    if smtps is False:
        pass
    else:
        result['SMTP'] = True
    if users >= 1 and smtps is True:
        code = 200
    return jsonify(result), code
